<template>
  <n-card :border="false">
    <n-alert type="warning" class="alert_small m-b-10">
      温馨提示：1.用户昵称/电话黄色为教师、绿色为普通用户；
      2.教师和普通用户提现手续费可能不一样、手续费可以到：设置->系统设置->提现设置中设置。
    </n-alert>
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="search_param" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="昵称/电话">
          <n-input v-model:value="search_param.key" placeholder="输入昵称或电话号码查询" clearable/>
        </n-form-item>
        <n-form-item label="提现方式">
          <n-select v-model:value="search_param.method" :options="methodOption" style="width: 130px;" clearable/>
        </n-form-item>
        <n-form-item label="状态">
          <n-select v-model:value="search_param.status" :options="statusOption" style="width: 130px;" clearable/>
        </n-form-item>
        <n-form-item>
          <search-button-group @submit="handleSubmitSearch"
                               @reset="()=>(search_param.key=null,search_param.status=null,search_param.method=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list"
                :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="search_param"
                list-url="user/withdrawa_list">
    </data-table>
  </n-card>
  <!-- 无效反馈意见 -->
  <n-modal v-model:show="feedbackModel"
           title="请输入未通过愿意" :mask-closable="false"
           :show-icon="false" preset="dialog"
           @after-leave="()=>(AuditForm.id=0,AuditForm.status=null,AuditForm.feedback='')">
    <n-input
        v-model:value="AuditForm.feedback"
        type="textarea"
        placeholder="输入信息不完整或有误!"
        :autosize="{minRows: 5}"/>
    <template #action>
      <n-space>
        <n-button @click="()=>(feedbackModel=false)">取消</n-button>
        <n-button type="primary" @click="AuditWithdrawal">提交</n-button>
      </n-space>
    </template>
  </n-modal>
  <!-- 修改-->
  <n-modal v-model:show="addEditModel"
           title="审核提现" :mask-closable="false"
           :show-icon="false" preset="dialog" style="width: 660px;" @after-leave="closeAddEditModel">
    <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
            label-width="auto" label-placement="left">
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="8" label="用户昵称:" :show-feedback="false">
          {{ addEditForm.nickname }}
          <!--           <n-input v-model:value="addEditForm.nickname" readonly/>-->
        </n-form-item-gi>
        <n-form-item-gi :span="4" label="ID:" :show-feedback="false">
          {{ addEditForm.id }}
        </n-form-item-gi>
        <n-form-item-gi :span="8" label="头像:" style="position: absolute;right: 10px;">
          <div>
            <div class="select-img" style="width: 100px;height: 100px;border:none;"
                 :class="appStore.theme=='light'?'light-img':'dark-img'">
              <div class="select-img-img">
                <template v-if="addEditForm.avatar">
                  <n-image
                      width="100"
                      :src="Config.VIEW_FILE+addEditForm.avatar"
                  />
                </template>
              </div>
            </div>
          </div>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="12" label="电话:" :show-feedback="false">
          {{ addEditForm.phone }}
          <!--          <n-input v-model:value="addEditForm.phone" maxlength="11" placeholder="用户电话号码" clearable/>-->
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="8" label="申请提现金额:" :show-feedback="false">
          {{ addEditForm.money && addEditForm.money.toFixed(2) }}
          <!--          <n-input-group>-->
          <!--            <n-input-number v-model:value="addEditForm.money" :min="0" :precision="2" :show-button="false"-->
          <!--                            placeholder="用户提现余额、请谨慎操作" clearable/>-->
          <!--            <n-input-group-label>元</n-input-group-label>-->
          <!--          </n-input-group>-->
        </n-form-item-gi>
        <n-form-item-gi :span="10" label="申请提现方式:" :show-feedback="false">
        {{appMethodName}}
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="20" label="提现账户:" :show-feedback="false">
          {{ addEditForm.account }}
          <!--          <n-input  v-model:value="addEditForm.account" placeholder="提现账户" clearable/>-->
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="20" label="备注:" :show-feedback="false">
          {{ addEditForm.remark }}
          <!--          <n-input  v-model:value="addEditForm.account" placeholder="提现账户" clearable/>-->
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="12" label="提现方式:" path="method">
          <n-select v-model:value="addEditForm.method" placeholder="提现方式" :options="methodOption" clearable/>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="20" label="提现金额:" path="amount">
          <n-input-group>
            <n-input-number v-model:value="addEditForm.amount" :min="0" :precision="2" :show-button="false"
                            placeholder="提现金额" clearable/>
            <n-input-group-label>元</n-input-group-label>
          </n-input-group>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="20" label="审核意见:" path="feedback">
          <n-input
              v-model:value="addEditForm.feedback"
              type="textarea"
              placeholder="审核意见"
              :autosize="{minRows: 3}"/>
        </n-form-item-gi>
      </n-grid>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="()=>(addEditModel=false)">取消</n-button>
        <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
import {ref, reactive, h, computed} from 'vue';
import SearchButtonGroup from '@components/SearchButtonGroup';
import {SelectOption, NTag, useMessage, NImage, FormInst, FormItemRule, NAvatar, NEllipsis} from 'naive-ui';
import DataTable from '@components/DataTable';
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import {UseAppStore} from '@/stores/app.ts';
import {Config} from "@/config";
import {postPutRequest, postRequest} from "@/api/data.ts";

const message = useMessage()
const appStore = UseAppStore();
//'状态  0:待审核 1:审核通过 2：审核未通过 4:无效 9:取消',
const statusOption = ref<SelectOption[]>([
  {
    label: '待审核',
    value: 0,
  }, {
    label: '审核通过',
    value: 1,
  }, {
    label: '审核未通过',
    value: 2,
  }, {
    label: '无效',
    value: 4,
  }, {
    label: '取消',
    value: 9,
  }
])
//0:微信 1:支付宝 2：银行卡 3:账号余额
const methodOption = ref<SelectOption[]>([
  {
    label: '微信',
    value: 0,
  }, {
    label: '支付宝',
    value: 1,
  }, {
    label: '银行卡',
    value: 2,
  }, {
    label: '账号余额',
    value: 3,
  }, {
    label: '线下提现',
    value: 4,
  }
])
const search_param = ref({
  key: null,
  status: null,
  method: null,
})
//无效反馈意见
const feedbackModel = ref<boolean>(false);
const AuditForm = ref({
  id: 0,
  status: <number | null>null,
  feedback: '',
})
//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: '头像',
    key: 'avatar',
    width: 60,
    align: 'center',
    render(row: { avatar: string }) {
      if (row.avatar) {
        return h(NAvatar, {
          size:30,
          src:  Config.VIEW_FILE + row.avatar
        })
      }
    }
  }, {
    title: '昵称/电话',
    key: 'nickname',
    width: 150,
    render(row:{nickname:string,phone:string|null,isTeacher:number}){
      const userType=row.isTeacher==1?'#f0a020':'#18a058'
      // const userTypeText=row.isTeacher==1?'教师':'普通用户'
      return h('div', {style: {width: '100%',color:userType}}, {
        default: () => (
            [h(NEllipsis, {style: {display: 'block'}}, {default: () => (row.nickname)}),
              h('span', null, {default: () => (row.phone)}),
              // h(NTag,
              //     {
              //       type: enabled_color,
              //     },
              //     {
              //       default: () => (enabled_text),
              //     }
              // )
            ])
      })
    }
  }, {
    title: '申请金额(元)',
    key: 'money',
    width: 130,
    align: 'center',
    render(row: { money: number }) {
      return h('span', null, {default: () => (row.money.toFixed(2))})
    }
  }, {
    title: '申请提现方式',
    key: 'appMethod',
    width: 110,
    render(row: { appMethod: number }) {
      const method_text: SelectOption | undefined = methodOption.value.find(obj => obj.value === row.appMethod);
      return h('span', null,
          {
            default: () => (method_text && method_text.label),
          }
      );
    }
  }, {
    title: '提现金额',
    key: 'amount',
    align: 'center',
    width: 130,
    render(row: { amount: number }) {
      return h('span', null, {default: () => (row.amount.toFixed(2))})
    }
  }, {
    title: '提现方式',
    key: 'method',
    width: 100,
    render(row: { method: number }) {
      const method_text: SelectOption | undefined = methodOption.value.find(obj => obj.value === row.method);
      return h('span', null,
          {
            default: () => (method_text && method_text.label),
          }
      );
    }
  },{
    title:'手续费(%)',
    key:'comRate',
    width:110,
    align: 'center',
  },{
    title:'最终提现(元)',
    key:'finalAmount',
    width:100,
    align: 'center',
  }, {
    title: '提现账户',
    key: 'account'
  },{
    title: '备注',
    key: 'remark'
  }, {
    title: '审核状态',
    key: 'status',
    width: 100,
    align: 'center',
    render(row: { status: boolean | number }) {
      //  status -- 0:待审核 1:审核通过 2：审核未通过  9:取消
      let enabled_color: any = '';
      let enabled_text = '';
      switch (row.status) {
        case 0:
          enabled_color = 'default';
          enabled_text = '待审核';
          break;
        case 1:
          enabled_color = 'success';
          enabled_text = '审核通过';
          break;
        case 2:
        case 4:
          enabled_color = 'error';
          if (row.status === 2) {
            enabled_text = '审核未通过';
          }
          if (row.status === 4) {
            enabled_text = '无效';
          }
          break;
        case 9:
          enabled_color = 'warning';
          enabled_text = '取消';
          break;
      }
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  }, {
    title: '创建时间',
    key: 'createTime',
    width: 175,
  },
]);
//操作列
const actionColumn = reactive({
  width: 120,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '无效',
          onClick: handleUpStatus.bind(null, record, 4),
          type: 'error',
          permission: ['withdrawal:audit'],
          disabled: !!record.disabled,
        },
        // {
        //   label: '通过',
        //   type: 'warning',
        //   popConfirm: NPopconfirm,
        //   onPositiveClick: handleUpStatus.bind(null, record, 1),
        //   confirm: {
        //     text: '通过后无法撤销，请谨慎操作！',
        //     positiveText: '通过',
        //     negativeText: '让我再考虑一下'
        //   },
        //   permission: ['withdrawal:audit'],
        //   disabled: !!record.disabled,
        // },
        {
          label: '通过',
          onClick: handleApproved.bind(null, record),
          type: 'primary',
          permission: ['materials:edit'],
          disabled: !!record.disabled,
        },
      ]
    });
  },
});
//编辑用户
const addEditModel = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitLoading = ref<boolean>(false);

const addEditForm = ref({
  id: 0,
  nickname: null,
  phone: null,
  avatar: null,
  money: <number | null | any>null,
  method: null,
  account: null,
  remark: null,
  feedback: null,
  amount: <number | null>null,
  status: 0,
  appMethod:null,
})
const addEditFormRules = computed(() => {
  return {
    amount: {
      required: true,
      trigger: ['blur', 'input'],
      //message: '请填写短信模板编码',
      validator: (_rule: FormItemRule, value: number, callback: Function) => {
        if (!value) {
          callback('请填写提现金额');
        } else if (value > addEditForm.value.money) {
          callback('提现金额不得大于申请金额');
        } else {
          callback();
        }
      }
    },
    method: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择提现方式'
    },
    feedback: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写审核意见'
    }
  }
})
//申请提现方式
const appMethodName = computed(() => {
  const appMethod: SelectOption | undefined = methodOption.value.find(item => item.value == addEditForm.value.appMethod);
  return appMethod ? appMethod.label : null;
})
//查询
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
//修改状态
const handleUpStatus = (record: Recordable, status: number) => {
  AuditForm.value.id = record.id;
  AuditForm.value.status = status;
  feedbackModel.value = true;
}
const AuditWithdrawal = () => {
  feedbackModel.value = false;
  postRequest('user/audit_withdrawal', AuditForm.value).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
//修改
const handleApproved = (record: Recordable) => {
  addEditForm.value.id = record.id;
  addEditForm.value.nickname = record.nickname;
  addEditForm.value.phone = record.phone;
  addEditForm.value.avatar = record.avatar;
  addEditForm.value.money = record.money;
  addEditForm.value.account = record.account;
  addEditForm.value.remark = record.remark;
  addEditForm.value.appMethod = record.appMethod;
  addEditModel.value = true;
}
//提交修改数据
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      addEditForm.value.status = 1;
      postPutRequest('user/edit_withdrawal', addEditForm.value, 'PUT').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditModel.value = false;
              data_list.value.reload();
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.nickname = null;
  addEditForm.value.phone = null;
  addEditForm.value.avatar = null;
  addEditForm.value.money = null;
  addEditForm.value.method = null;
  addEditForm.value.account = null;
  addEditForm.value.remark = null;
  addEditForm.value.feedback = null;
  addEditForm.value.amount = null;
  addEditForm.value.status = 0;
  handelSubmitLoading.value = false;
}

</script>

<style scoped lang="scss">

</style>